<?php

namespace App\Http\Resources;

use App\Models\CommentHide;
use Illuminate\Http\Resources\Json\JsonResource;

class CommentHideResource extends CommentDetailResource
{
    private static $canSeeTopicHideCache;
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $route = $request->route();
        $tid = $route->parameter('topic');
        if (empty($tid)) {
            throw new \RuntimeException("路由错误，无 tid");
        }
        if (isset(self::$canSeeTopicHideCache[$tid])) {
            $canSeeTopicHide = self::$canSeeTopicHideCache[$tid];
        } else {
            $user = auth_user();
            $canSeeTopicHide = $user->canSeeTopicHide($tid);
            //进行缓存
            self::$canSeeTopicHideCache[$tid] = $canSeeTopicHide;
        }

        $results = [
            'id' => $this->id,
            'cid' => $this->cid,
            'require_score' => $this->require_score,
            'require_reply' => $this->require_reply,
            'require_header' => $this->getRequireHeaderAttribute($this->resource, $canSeeTopicHide),
        ];

        if ($canSeeTopicHide['result']) {
            $results['content'] = $this->normalizeContent($this->content);
            $results['can_be_seen'] = 1;
        } else {
            $results['content'] = [];
            $results['can_be_seen'] = 0;
            if ($this->require_score && !$canSeeTopicHide['has_buy']) {
                $results['btn_purchase_text'] = sprintf('支付 %s 积分查看隐藏内容', $this->require_score);
            }
        }


        return $results;

    }

    private function getRequireHeaderAttribute(CommentHide $commentHide, $canSeeTopicHide)
    {
        $desc = "以下为隐藏内容";
        $require = [];
        if (!$canSeeTopicHide['result']) {
            if ($commentHide->require_reply && !$canSeeTopicHide['has_reply']) {
                $require[] = "回复本帖";
            }
            if ($commentHide->require_score && !$canSeeTopicHide['has_buy']) {
                $require[] = "花费 {$commentHide->require_score} 积分购买";
            }
            if (empty($require)) {
                return $desc;
            }
        }

        if (empty($require)) {
            return $desc;
        } else {
            return sprintf("%s, 需要 %s 可见", $desc, implode('，', $require));
        }

    }

}
